import React, {useEffect, useState} from 'react'
import type {ColumnsType} from 'antd/es/table'
import {
	Button,
	Form,
	DatePicker,
	Modal,
	Table,
	Upload,
	message,
	Select,
} from 'antd'
import {PlusOutlined} from '@ant-design/icons'
import moment from 'moment'
import type {UploadFile} from 'antd/es/upload/interface'
import {useModel} from 'umi'
import styles from './index.less'
import {getPublicDownloadUrl, uploadFileUrl} from '@/service/common/upload'

interface DataType {
	priceFileName: string
	imgHrefs: any[]
	supplierCode: string
	supplierName: string
	bidSection: string
	bidOpeningTime: string
	priceFileUrl: string
}
interface ModelTableType {
	supplierCode: string
	supplierName: string
	contacts: string
	bidderPhone: string
}

type PropsType = {
	type: string | undefined
	answerData: any[]
	bidOpeningData: any[]
	setBidOpeningData: React.Dispatch<React.SetStateAction<any[]>>
	dictData: any
}

const bidOpeningRecord = (props: PropsType) => {
	const {type, answerData, bidOpeningData, setBidOpeningData, dictData} =
		props
	const {initialState} = useModel('@@initialState')
	const {fileName} = initialState || {}
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [form] = Form.useForm()
	const [supplierData, setSupplierData] = useState<any>({})
	const [fileList, setFileList] = useState<UploadFile[]>([])
	const [dataSource, setDataSource] = useState<any[]>([])
	useEffect(() => {
		if (isModalOpen === false) {
			const newData = [...answerData]
			const arr = []
			for (let i = 0; i < newData.length; i += 1) {
				let isExist = false
				for (let j = 0; j < bidOpeningData.length; j += 1) {
					if (
						newData[i].supplierCode ===
						bidOpeningData[j].supplierCode
					) {
						isExist = true
						break
					}
				}
				if (!isExist) {
					arr.push(newData[i])
				}
			}
			setDataSource(arr)
			setSupplierData(undefined)
		} else {
			setFileList([])
		}
	}, [isModalOpen, answerData, bidOpeningData])

	const columns: ColumnsType<DataType> = [
		{
			title: '投标供应商',
			dataIndex: 'supplierName',
			align: 'center',
		},
		{
			title: '供应商编号',
			dataIndex: 'supplierCode',
			align: 'center',
		},
		{
			title: '投标标段',
			dataIndex: 'bidSection',
			align: 'center',
			render: (text) => (
				<Select
					value={text}
					disabled
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.Project_Bid_Section}
				/>
			),
		},
		{
			title: '开标时间',
			dataIndex: 'bidOpeningTime',
			align: 'center',
		},
		{
			title: '开标报价文件',
			dataIndex: 'priceFileName',
			align: 'center',
			render: (text: any, record) => {
				const name = record?.priceFileName?.split(',') || []
				return (
					<p>
						{name?.map((item: string, index: number) => (
							<a
								style={{marginRight: '10px', display: 'block'}}
								href={record?.imgHrefs?.[index]?.url}
								download>
								{item}
							</a>
						))}
					</p>
				)
			},
		},
	]
	const columnModel: ColumnsType<ModelTableType> = [
		{
			title: '投标供应商',
			dataIndex: 'supplierName',
			align: 'center',
		},
		{
			title: '供应商编号',
			dataIndex: 'supplierCode',
			align: 'center',
		},
		{
			title: '投标联系人',
			dataIndex: 'bidderPerson',
			align: 'center',
		},
		{
			title: '联系电话',
			dataIndex: 'bidderPhone',
			align: 'center',
		},
	]

	const normFile = (e: any) => {
		if (Array.isArray(e)) {
			return e
		}
		return e?.fileList
	}

	const rowSelection = {
		onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {
			setSupplierData(selectedRows[0])
		},
		getCheckboxProps: (record: any) => ({
			name: record.supplierCode,
		}),
	}

	const onCancel = () => {
		form.resetFields()
		setIsModalOpen(false)
	}
	const submit = async () => {
		if (!supplierData) {
			message.warning('请选择投标供应商')
		} else {
			const newData = [...bidOpeningData]
			const value = await form.validateFields()
			const priceFileUrl = fileList?.map(
				(item) => item?.response?.data?.id || item?.uid,
			)
			const priceFileName = fileList?.map(
				(item) => item?.response?.data?.filename || item?.name,
			)
			if (value) {
				const datas: any = {
					supplierName: supplierData.supplierName,
					supplierCode: supplierData.supplierCode,
					contacts: supplierData.contacts,
					bidSection: supplierData.bidSection,
					telephone: supplierData.telephone,
					bidOpeningTime: moment(value?.bidOpeningTime).format(
						'YYYY-MM-DD HH:mm',
					),
					priceFileUrl: priceFileUrl?.toString(),
					priceFileName: priceFileName?.toString(),
				}
				getPublicDownloadUrl(priceFileUrl?.map(Number))
					.then((res: any) => {
						if (res?.success) {
							datas.imgHrefs = res?.data
							newData.push(datas)
							setBidOpeningData(newData)
							form.resetFields()
							setIsModalOpen(false)
						}
					})
					.catch((err: any) => {
						message.error(err)
					})
			}
		}
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileName,
		data: {
			modelName: 'spBidding',
			targetAttr: 20,
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				setFileList(info?.fileList)
			}
			setFileList(info?.fileList)
		},
		fileList,
	}

	return (
		<div className={styles.bidOpeningRecord}>
			<div className={styles.btnlist}>
				{type !== 'view' ? (
					<Button
						icon={<PlusOutlined />}
						type="primary"
						ghost
						size="small"
						onClick={() => {
							setIsModalOpen(true)
						}}>
						新增记录
					</Button>
				) : (
					''
				)}
			</div>
			<Table
				columns={columns}
				dataSource={bidOpeningData}
				pagination={false}
				loading={false}
				bordered
			/>
			<Modal
				title="新增开标记录"
				open={isModalOpen}
				onOk={submit}
				onCancel={onCancel}
				width={700}
				className={styles.bidOpeningModal}
				destroyOnClose>
				<Table
					rowKey="supplierCode"
					rowSelection={{
						type: 'radio',
						...rowSelection,
					}}
					columns={columnModel}
					dataSource={dataSource}
					pagination={false}
					loading={false}
					bordered
				/>
				<Form
					form={form}
					name="basic"
					layout="horizontal"
					labelCol={{flex: '100px'}}
					labelAlign="right"
					labelWrap
					autoComplete="off"
					style={{marginTop: '12px'}}>
					<Form.Item
						label="开标时间"
						name="bidOpeningTime"
						rules={[{required: true}]}
						colon>
						<DatePicker
							placeholder={type === 'view' ? '-' : '请选择'}
							showTime
							format="YYYY-MM-DD HH:mm"
							style={{width: '200px'}}
						/>
					</Form.Item>
					<Form.Item
						name="priceFileUrl"
						label="标价文件"
						valuePropName="fileList"
						getValueFromEvent={normFile}
						rules={[{required: true, message: '请上传标价文件'}]}
						className={styles.fileUpload}>
						<Upload {...uploadProps}>
							{fileList.length >= 5 ? null : (
								<Button>请选择文件</Button>
							)}
						</Upload>
					</Form.Item>
					<div className={styles.uploadTip}>
						附件说明：支持格式rar .zip .doc .docx .pdf .jpg .png
						.xlsx .xls等,每个文件最大为200MB,最多可上传5个文件
					</div>
				</Form>
			</Modal>
		</div>
	)
}

export default bidOpeningRecord
